﻿use strict;

use LWP::Simple;
use HTML::TokeParser;
use XML::RSS;
use DateTime;
use DateTime::Format::Mail;
use DateTime::TimeZone;
use Encode;
use URI;

my $debug = ( @ARGV[0] eq "debug" );
my $baseurl = 'http://look.jojohot.com/jojoindex-bbs.htm';
my $content = get($baseurl) or die $!;
my $stream = HTML::TokeParser->new(\$content ) or die $!;
my $rss = XML::RSS->new (version => '2.0' );

$rss->channel(
    title => "Jojohot 热情动漫汉化研究 comics update", link => $baseurl, description => "Jojohot comic translation news 动漫是虚幻的…你我的人生是真实的…奉献需要热情！…幸福是用真心感受的……！",
    lastBuildDate => DateTime::Format::Mail->format_datetime(DateTime->now), webMaster => 'chunju+jojohot@gmail.com', managingEditor => 'jojohotcom@sina.com', language => 'zh-cn');

my @itemlist;
my $tag;

my ($date);
my $goon = 1;
while($goon)
{
    $tag = $stream->get_tag('p');
    if( $tag->[1]{class} eq 'style10' )
    {

        # date right in the p tag
         my $x = $stream->get_trimmed_text('br', '/p', 'a');
if($debug) {print "date string: $x\n";}
         if(length($x) > 0)
         {
             $x =~ /(\d{1,2})\D*(\d{1,2}).*/;
if($debug) {print "stript month: ($1) day: ($2)\n";}
             $date = DateTime::Format::Mail->format_datetime(DateTime->new( year => DateTime->now->year, month => $1, day => $2, time_zone => 'Asia/Taipei'));
         }

        while($goon)
        {
            $tag = $stream->get_tag('br', '/div', 'a');
            if($tag->[0] eq '/div') 
            {
                $goon = "";
            }
            elsif($tag->[0] eq 'a') 
            {
                 my $a = $tag->[1]{href};
                 if( !($a =~ /http.*/)) {$a = URI->new_abs($a, $baseurl);}
if($debug) {print "url found: $a\n";}
                 my $t = $stream->get_trimmed_text('/a');
                 Encode::from_to($t, "gb2312", "utf8");
                 $itemlist[$#itemlist+1]={headline=>$t, url=>$a, time=>$date};
                 my $l = length($t);
                 $t =~ s/\D//g;
if($debug) {print "item added. title:[$t/$l] url:[$a] time:[$date]\n";}
            }
            else 
            {
                my $b = $stream->get_trimmed_text('br', '/p', 'a');
if($debug) {print "date string: $b\n";}
                if(length($b) > 0) 
                {
                   $b =~ /(\d{1,2})\D*(\d{1,2}).*/;
if($debug) {print "stript month: ($1) day: ($2)\n";}
                   $date = DateTime::Format::Mail->format_datetime(DateTime->new( year => DateTime->now->year, month => $1, day => $2, time_zone => 'Asia/Taipei'));
                }
            }
        }
    }
}

foreach (@itemlist)
{
# print $_->{headline}, "--", $_->{url}, "--", $_->{desc}, "\n";
#print $_->{url}, "    ";
#    $_->{url} =~ /\/([^\/]+)\/[^\/]+\.htm.*/;
#print $_->{url}, "\n";
    $rss->add_item( title => $_->{headline}, link => $_->{url}, pubDate => $_->{time}, guid => $1.'_'.$_->{time});
}

$rss->save("jojohot.rss") or die$!;
my $now = DateTime->now;
print "jojohot.rss created -$now\n";
